package com.szx.kaihei.validators;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.Field;

public class NInNValidator implements ConstraintValidator<ValidNInN, Object> {
    private String[] fields;
    private int number;
    @Override
    public void initialize(ValidNInN constraintAnnotation) {
        fields = constraintAnnotation.fields();
        number = constraintAnnotation.number();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
        if (fields.length < number){
            number = 1;
        }
        int total = 0;
        for (String field : fields) {
            try {
                Field declaredField = object.getClass().getDeclaredField(field);
                declaredField.setAccessible(true);
                Object value = declaredField.get(object);
                total = value == null ? total : total + 1;

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        constraintValidatorContext.disableDefaultConstraintViolation();
        constraintValidatorContext.buildConstraintViolationWithTemplate("只能且必须有" + number + "参数不为空").addConstraintViolation();


        return total == number;
    }
}
